<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\TaskServiceType\StoreTaskServiceTypeRequest;
use App\Http\Requests\Admin\TaskServiceType\UpdateTaskServiceTypeRequest;
use App\Models\Task;
use App\Models\TaskServiceType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TaskServiceTypeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $perPage = (int) $request->get('per_page', 15);
        $perPage = $perPage > 0 ? $perPage : 15;

        $query = TaskServiceType::query();

        if ($request->filled('keyword')) {
            $keyword = trim($request->get('keyword'));
            $query->where('name', 'like', '%' . $keyword . '%');
        }

        $paginator = $query
            ->orderByDesc('created_at')
            ->paginate($perPage);

        return response()->json([
            'code' => 0,
            'message' => '获取任务服务类型列表成功',
            'data' => [
                'items' => $paginator->items(),
                'pagination' => [
                    'total' => $paginator->total(),
                    'per_page' => $paginator->perPage(),
                    'current_page' => $paginator->currentPage(),
                    'last_page' => $paginator->lastPage(),
                ],
            ],
        ]);
    }

    public function store(StoreTaskServiceTypeRequest $request): JsonResponse
    {
        $serviceType = TaskServiceType::create($request->validated());

        return response()->json([
            'code' => 0,
            'message' => '服务类型创建成功',
            'data' => $serviceType,
        ], 201);
    }

    public function update(UpdateTaskServiceTypeRequest $request, TaskServiceType $taskServiceType): JsonResponse
    {
        $originalName = $taskServiceType->name;

        $taskServiceType->update($request->validated());

        if ($originalName !== $taskServiceType->name) {
            Task::where('service_type', $originalName)
                ->update(['service_type' => $taskServiceType->name]);
        }

        return response()->json([
            'code' => 0,
            'message' => '服务类型更新成功',
            'data' => $taskServiceType->fresh(),
        ]);
    }

    public function destroy(TaskServiceType $taskServiceType): JsonResponse
    {
        $inUse = Task::where('service_type', $taskServiceType->name)->exists();

        if ($inUse) {
            return response()->json([
                'code' => 422,
                'message' => '该服务类型已被任务使用，无法删除',
                'data' => null,
            ], 422);
        }

        $taskServiceType->delete();

        return response()->json([
            'code' => 0,
            'message' => '服务类型已删除',
            'data' => null,
        ]);
    }
}
